<template>
	<view class="body" >
		<myHead :title="title" />
		<uni-popup ref="popup1" type="center">
				<uni-forms-item label="文件名称" name="age">
				       <input type="text" v-model="file.fileName" placeholder="请输入文件名称"  />
				 </uni-forms-item>
				 <button type="default"class="add" @click="commit_add()" >新增</button>
		</uni-popup>
		<uni-nav-bar >
			<view slot="default">
				<uni-easyinput
				 prefixIcon="search"
				  v-model="fileName"
				  placeholder="请输入内容"
				  @iconClick="onClick"
				  autoHeigh
				   @confirm="confirm" >
				  </uni-easyinput>
			</view>
			  <view slot="left" class="right" @click="his_back()">
				 <image src="../../static/party_building/assets/files/back.png"   mode=""></image>
			  </view>
			  <view slot="right" class="right">
				   <image @click="$refs.popup.open('top')"
					src="../../static/party_building/assets/files/create.png" mode=""
					class="add_dir" :style="'z-index: 9;'"></image>
				   <!-- 图片上传 -->
				   <uni-file-picker
				    v-model="imageValue" 
					style="
					position: absolute;
					opacity: 0;
					z-index: 1;
					top: 1%;" 
					
			limit="1" :auto-upload="true" mode="list" file-mediatype="all" @select="select">
				   </uni-file-picker>
					<image src="../../static/party_building/assets/files/upload.png" mode=""></image>
			  </view>
		</uni-nav-bar>
		<!-- 弹出层 -->
		<uni-popup ref="popup" type="center" background-color="#fff">
			<uni-forms-item label="目录名称" name="age">
			       <input type="text" v-model="dir_name" placeholder="请输入目录名称"  />
			 </uni-forms-item>
			 <button type="default"class="add" @click="dir_add()" >新增</button>
		</uni-popup>
	<!-- 按组使用 -->
	<scroll-view scroll-y="true"  class="scroll-Y" :style="'height:'+height+'px'" >
	<uni-swipe-action>
	    <uni-swipe-action-item
		 class="d_img"  :threshold="20"
		 v-for="(item,key) in directory" :right-options="options" >
				<view @click="bindClick(item.id)" ><image src="../../static/party_building/assets/files/directory.png" mode=""></image>
				<span class="front">{{item.path}}</span></view>
				<span class="time">{{item.createTime}}</span>
			<template v-slot:right>
				<view>
					<image 
					 src="../../static/party_building/assets/files/delete.png" 
					@click="deleteFile(item.id)" class="delete" mode="">
					</image>
				</view>
			</template>
	    </uni-swipe-action-item>
		<!-- 文件 --> 
		    <uni-swipe-action-item
			 class="d_img"   :threshold="20"
			 v-for="(item,key) in files" >
		   <!--   <a :hrf="item.url" :download="item.url"> -->
				  <view  @click="$api(item.url)" ><image  src="../../static/party_building/assets/files/files.png" mode=""></image>
				<span class="front">{{item.fileName}}</span></view>
				<span class="time">{{item.createTime}}</span>
				<!-- </a> -->
			<template v-slot:right>
				<view>
					<image @click="deleteFile(item.id)"
					 src="../../static/party_building/assets/files/delete.png"
					  class="delete" mode=""></image>
				</view>
			</template>
		    </uni-swipe-action-item>
	</uni-swipe-action>
		
	</scroll-view>
	</view>
</template>

<script>
	import {d_delete,d_download,d_upload,byFileNameGetInfo} from '@/api/api_camp.js'
	import myHeader from '../components/head.vue'
	export default {
		data(){
			return {
				title:"资料集中营",
				dir_name:'',
				fileName:'',
				file:{},
				imageValue:[],
				history:[0],//栈对象
				id:'',//当前页
				directory:[],
				index:0,//当前索引
				files:[],
				n:0,
				height:500,
				value:'',//shousuo
				  options:[
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				  ],
				
			}
		},components:{
				myHead:myHeader,
			},
			create(){
			},mounted() {
				this.height = uni.getSystemInfoSync().screenHeight*0.8
				this.init()
			},
		methods: {
			shareSystem(){
							plus.share.sendWithSystem({type:'text',content:'求是党建邀请您下载文件:',href:'http://112.124.6.140:8090/downloadFile/2021/6/27/1624790109200.docx'}, function(){
								uni.showModal({
									title:'分享成功!'
								})
							}, function(e){
								console.log('分享失败：'+JSON.stringify(e));
							});
						},
			onClick(e){
				console.log(e)
			  console.log('点击了'+(e.position === 'left' ? '左侧' : '右侧') + e.content.text + '按钮')
			},
			swipeChange(e,index){
				console.log(e)
			  console.log('当前状态：'+ open +'，下标：' + index)
			},
			confirm(){
				let _this = this 
				byFileNameGetInfo({
					fileName:this.fileName
				}).then(res=>{
					_this.files = res
					_this.directory = []
				})        
			},bindClick(e){
				this.history.push(this.index)
				this.index = e
				this.init()
			},deleteFile(id){
				let _this = this 
				uni.showModal({
					title: '提示',
					content: '受否确认删除？',
					success: function(res) {
							if(res.confirm){
								d_delete({
									id:id
								}).then(res=>{
									_this.init()
								})
							}
						},
						})
			},init(){
				d_download({id:this.index}).then(res=>{
					this.directory = res.lists
					this.files = res.files
				})
			},getFile(url){
						var url = 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3101694723,748884042&fm=26&gp=0.jpg'; //文件名称可以在上传时进行保存，下载时取出，当文件名称中存在单双引号时，要做好处理，否则会报错
						var name = 'z.jpg';
						
						plus.downloader
							.createDownload(
								url,
								{
									filename: '_downloads/' + name //利用保存路径，实现下载文件的重命名
								},
								function(d, status) {
									//d为下载的文件对象
									if (status == 200) {
										//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
										console.log(d);
										let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
										console.log(fileSaveUrl);
										//进行DOM操作
										$('#downloadImg').attr('src', fileSaveUrl);
										plus.runtime.openFile(d.filename);	   //选择软件打开文件
										
									} else {
										//下载失败
										plus.downloader.clear(); //清除下载任务
									}
								}
							).start();
							uni.showToast({
								title:fileSaveUrl
							})
						
			},playpapers(url){
				let _this = this
				uni.showModal({
					title:'提示',
					content:'是否确定1下载',
					  success: function (res) {
					        if (res.confirm) {
					            let dload = document.createElement("a");
					            dload.download = '';// 设置下载的文件名，默认是'下载'
					            dload.href = url;
					            document.body.appendChild(dload);
					            dload.click();
					            dload.remove(); // 下载之后把创建的元素删除
					            uni.showToast({
					            title: "成功",
					            icon: "success"
					            });
					        } 

				  },
				})
				},
				download(url) {
					window.open(url)
					const iframe = document.createElement("iframe");
					iframe.style.display = "none"; // 防止影响页面
					iframe.style.height = 0; // 防止影响页面
					iframe.src = url;
					document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
					// 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
					setTimeout(() => {
						iframe.remove();
					}, 5 * 60 * 1000);
				},
				 createDownload(url) {
					 if(window.plus){ 
					     
					     var dtask = plus.downloader.createDownload(url, {}, function(d, status){
					     	// 下载完成
					     	if(status == 200){ 
					     		uni.showToast({
					     			title:d.filename+"成功"+status
					     		})
					     		console.log("Download success: " + d.filename);
					     	} else {
					     		uni.showToast({
					     			title:'Download failed'+status,
					     			icon:'none'
					     		})
					     		 console.log("Download failed: " + status); 
					     	}  
					     });
					     //dtask.addEventListener("statechanged", onStateChanged, false);
					     dtask.start(); 
					 }else{// 兼容老版本的plusready事件 
					     document.addEventListener('plusready',function () { 
					        
					        var dtask = plus.downloader.createDownload(url, {}, function(d, status){
					        	// 下载完成
					        	if(status == 200){ 
					        		uni.showToast({
					        			title:d.filename+"成功"+status
					        		})
					        		console.log("Download success: " + d.filename);
					        	} else {
					        		uni.showToast({
					        			title:'Download failed'+status,
					        			icon:'none'
					        		})
					        		 console.log("Download failed: " + status); 
					        	}  
					        });
					        //dtask.addEventListener("statechanged", onStateChanged, false);
					        dtask.start(); 
					     },false); 
					 } 
				},
				saveImg: function(url){
					var oA = document.createElement("a");
					oA.download = '';// 设置下载的文件名，默认是'下载'
					oA.href = url;
					document.body.appendChild(oA);
					oA.click();
					oA.remove(); // 下载之后把创建的元素删除
				},
			his_back(){
				if(this.index === 0){
					this.init()
					return
				}
				this.index = this.history.pop();
				this.init()
			},dir_add(){
				if(this.dir_name.length<=0){
					uni.showToast({
						title:'请输入名称',
						duration:2000,
						icon:'none'
					})
					return
				}
				let _this = this 
				d_upload({
					fileName: "",
					path: _this.dir_name,
					pid: _this.index,
					status: 1,
					type: 0,
				}).then(res=>{
					_this.dir_name = '';
					uni.showToast({
						title:'新建成功',
						duration:2000,
						success() {
							_this.$refs.popup.close()
							_this.dir_name = '';
							_this.init()
						},complete() {
						}
					})
				})
			},select(e){
				let _this = this 
				let source = e.tempFiles[0];
				let token = uni.getStorageSync("AuthToken");
				uni.uploadFile({
					url: '/api/uploadFile', //仅为示例，非真实的接口地址
					filePath: e.tempFilePaths[0],
					name: 'file',
					header: {
						'x-access-token': token
					},
					formData: {
						'name': source.name,
						'size': source.size
					},
					success: (res) => {
						let  data = JSON.parse( res.data).data
						console.log(data)
						_this.file={
							fileName: data.fileName,
							path: data.fileName,
							pid: _this.index,
							status: 0,
							type: 0,
							url: data.url
						}
						_this.$refs.popup1.open('top')
					},complete() {
						_this.imageValue = []
					}
				});
			},commit_add(){
				let _this = this
				let data = this.file
				d_upload({
					fileName: data.fileName,
					path: data.fileName,
					pid: this.index,
					status: 0,
					type: 0,
					url: data.url
				}).then(res=>{
					_this.init()
					_this.$refs.popup1.close()
					setTimeout(
					uni.showToast({
						title:'新建成功',
						duration:2000,
						success() {
							
						},complete() {
						}
					})
					,500)
				}).catch(res=>{
						uni.showToast({
							title:'新建失败',
							duration:2000,
							success() {
							},complete() {
							}
						})
				})
			}
		},
	}
</script>
<style lang="scss" scoped>	


	/**
	 * 定义按钮样式
	 */
	@mixin button-commit {
		background: linear-gradient(180deg, #ff5e59, #e20909);
		color: #fff;
	}
	.body{
		/deep/ .uni-popup__wrapper-box{
			background-color: #FFF;
			padding: 10%;
			border-radius: 10px;
			.add{
				@include button-commit;
			}
		}
		/deep/ .uni-navbar{
			.uni-navbar__header-container{
				
				.uni-easyinput{
					width: 100%!important;
				}
			}
			.uni-navbar__header-btns{
				width: auto !important;
				
			}
			uni-image{
				width: 70upx!important;
				height: 70upx!important;
				display: inline-block;
				// box-shadow: 1upx 1upx 1upx 1upx  #d4d4d4;
				position: relative;
				top:20upx;
				margin: 0 5px;
			}
		}
		
		/deep/ .d_img{
			uni-image{
				width: 70upx;
				height: 70upx;
				margin-left: 2%;
			}
			.front{
				position: absolute;
				top: 15%;
				margin-left: 2%; 
				width: 45%;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
			.time{
				float: right;
				position: relative;
				top: -50%;
				margin-right: 2%;
			}
			.delete{
				width: 70upx;
				height: 70upx;
				margin-left: 2%;
				background-color: red;
			}
		}
		}
</style>